package com.tanhua.dubbo.api.utils;

import io.jsonwebtoken.*;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtil {


    public static String createToken(Map map) {
        //生成token
        //使用JWT的工具类生成token
        long now = System.currentTimeMillis();
        String token = Jwts.builder()
                .signWith(SignatureAlgorithm.HS512, "itcast") //指定加密算法
                .setClaims(map) //写入数据
                .setExpiration(new Date(now + 30000000)) //失效时间
                .compact();
        System.out.println(token);
        return token;
    }

    //解析token

    /**
     * SignatureException : token不合法
     * ExpiredJwtException：token已过期
     */
    public static boolean verifyToken(String token) {
        try {
            Claims claims = Jwts.parser()
                    .setSigningKey("itcast")
                    .parseClaimsJws(token)
                    .getBody();
            Object id = claims.get("id");
            Object mobile = claims.get("mobile");
            System.out.println(id + "--" + mobile);
        }catch (ExpiredJwtException e) {
            System.out.println("token已过期");
            return false;
        }catch (SignatureException e) {
            System.out.println("token不合法");
            return false;
        }
        return true;
    }

    public static Claims getClaims(String token) {
        try {
            Claims claims = Jwts.parser()
                    .setSigningKey("itcast")
                    .parseClaimsJws(token)
                    .getBody();
            Object id = claims.get("id");
            Object mobile = claims.get("mobile");
            System.out.println(id + "--" + mobile);
            return claims;
        }catch (ExpiredJwtException e) {
            System.out.println("token已过期");
            return null;
        }catch (SignatureException e) {
            System.out.println("token不合法");
            return null;
        }

    }


    public static Long parseToken(String token){
        //1 解析token，获取id
        boolean flag = JwtUtil.verifyToken(token);
        if (!flag){
            return -1l;
        }
        //验证通过
        Claims claims = JwtUtil.getClaims(token);
        Long id = Long.valueOf(claims.get("id").toString());
        return id;
    }


}
